package com.xpffly.design.composite.common;

import com.xpffly.design.composite.common.service.Component;
import com.xpffly.design.composite.common.service.impl.Composite;
import com.xpffly.design.composite.common.service.impl.Leaf;

/**
 * @Author: 午夜学徒
 * @Date: 2022/3/26 11:19
 * @Description：组合模式通用代码场景类
 */
public class Scene {
    public static void main(String[] args) {
        // 创建一个根节点
        Composite root = new Composite();
        root.doSomething();
        // 创建一个树枝构件
        Composite branch = new Composite();
        // 创建一个叶子构件
        Leaf leaf = new Leaf();
        Leaf leaf2 = new Leaf();
        // 建立整体树状结构
        root.add(branch);
        branch.add(leaf);
        branch.add(leaf2);
        display(root);
    }

    /**
     * 通过递归遍历树
     *
     * @param root 根节点
     */
    public static void display(Composite root) {
        for (Component c :
                root.getChildren()) {
            if (c instanceof Leaf) {
                // 叶子节点
                c.doSomething();
            } else {
                // 树枝节点
                display((Composite) c);
            }
        }

    }
}
